<template>
  <AModal
    v-model:visible="visible"
    unmount-on-close
    :title="title"
    :width="width"
    v-bind="modalAttr"
    :mask-closable="maskClosable"
    :on-before-ok="handleBeforeOk"
  >
    <table-search
      :fileds="searchFileds"
      @search="search"
      @reset="search"
    ></table-search>
    <xTable
      v-model:refresh="refresh"
      v-model:selected-keys="selectedKeys"
      :params="{ ...props.params, ...params }"
      :columns="tableColumns"
      row-key="userId"
      :http="{
        list: unallocatedUserList,
      }"
    >
      <template #status="{ row }">
        <dict-tag :options="dict.sys_normal_disable" :value="row.status" />
      </template>
    </xTable>
  </AModal>
</template>

<script lang="ts" setup>
  import { ref, reactive } from 'vue';
  import { getDict } from '@/utils/dict';
  import { Message } from '@arco-design/web-vue';
  import { unallocatedUserList, authUserSelectAll } from '@/api/system/role';

  const emit = defineEmits(['reload']);
  const dict = getDict('sys_normal_disable');
  const props = defineProps({
    // modal宽度
    width: {
      type: [String, Number],
      default: '900px',
    },
    title: {
      type: String,
      default: '选择用户',
    },
    params: {
      type: Object,
      default: () => ({}),
    },
    // 点击蒙层是否允许关闭
    maskClosable: Boolean,
    // 对话框额外参数
    modalAttr: Object,
  });
  const visible = ref(false);
  const loading = ref(false);
  const refresh = ref(true);
  const params = ref({});
  const selectedKeys = ref([]);
  const searchFileds = reactive([
    {
      span: 9,
      field: 'userName',
      placeholder: '请输入用户名称',
      label: '用户名称',
      tag: 'a-input',
      initValue: '',
    },
    {
      span: 9,
      field: 'phonenumber',
      placeholder: '请输入手机号码',
      label: '手机号码',
      tag: 'a-input',
      initValue: '',
    },
  ]);
  const tableColumns = reactive([
    {
      title: '用户名称',
      dataIndex: 'userName',
    },
    {
      title: '用户昵称',
      dataIndex: 'nickName',
    },
    {
      title: '邮箱',
      dataIndex: 'email',
    },
    {
      title: '手机',
      dataIndex: 'phonenumber',
    },
    {
      title: '状态',
      dataIndex: 'status',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
    },
  ]);

  const show = () => {
    loading.value = false;
    visible.value = true;
    refresh.value = true;
  };
  const search = (data: any) => {
    params.value = data;
    refresh.value = true;
  };
  const handleBeforeOk = (done: any) => {
    const userIds = selectedKeys.value.join(',');
    if (userIds === '') {
      Message.warning('请选择要分配的用户');
      return;
    }
    authUserSelectAll({ userIds, ...props.params }).then(({ code, msg }) => {
      if (code !== 200) {
        Message.error(msg);
        done(false);
      }
      emit('reload');
      done();
    });
  };
  defineExpose({
    show,
    visible,
  });
</script>

<style></style>
